package light.head.dao.sys;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


import light.head.cache.Cache;
import light.head.constant.Parm;
import light.head.enm.RESULT;
import light.head.framework.base.BaseDAO;
import light.head.framework.entity.PageBean;
import light.head.model.Role;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author janhang
 * @2010-12-16  下午03:59:29
 * 角色管理，相关Model有Role、RoleGroup、RoleHandle
 */
@Service
public class RoleDAO extends BaseDAO<Role, Integer> {
	
	private OrganDAO organDAO;		// 因为角色都是根机构的，所以这里处理传进来的所有机构编号，都获取根机构编号
	private final static String sql_delete = "DELETE RoleHandle rh WHERE rh.roleCode = ?";
	private final static String sql_updateDefaultRole = "UPDATE Role r SET r.isDefault = 0 WHERE r.isDefault = 1 AND r.oc = ?";
	private final static String sql_findByOrganCode = "FROM Role r WHERE r.oc = ? AND r.deleted <> 1";
	

	/**
	 * 因freemarker需使用该方法，所以参数必须使用String
	 * @param	机构编号
	 */
	public List<Role> getAllByOrgCode(String code) {
		if (!isNotNull(code)) return null;
		
		Integer c = organDAO.getRoot(Integer.parseInt(code)).getCode();
		List<Role> list = Cache.organRoleMap.get(c);
		if (null == list || list.size() == 0) {
			loadAllByOrgCode(c);
		}
		return Cache.organRoleMap.get(c);
	}
	
	/**
	 * 缓存机构对应角色列表
	 * @param c
	 */
	public RESULT loadAllByOrgCode(Integer oc){
		Integer c = organDAO.getRoot(oc).getCode();
		
		List<Role> list = find(sql_findByOrganCode, c);
		Cache.organRoleMap.put(c, list);
		return RESULT.SUCCESS;
		
	}
	
	
//	/**
//	 * 获取所有权限
//	 */
//	public List<Role> getAll() {
//		if (null == Cache.roleList) {
//			loadAll();
//		}
//		return Cache.roleList;
//	}
//	
//	/**
//	 * 加载所有权限
//	 */
//	public RESULT loadAll() {
//		Cache.roleList = find(sql_loadAll);
//		return RESULT.SUCCESS;
//	}
//	
	/**
	 * 获取指定机构的角色列表(完全是因为freemarker而存在)
	 * @param	机构编号
	 */
	public List<Role> findByOrganCode(String organCode) {
		if (!isNotNull(organCode))
			return null;
		return getAllByOrgCode(organCode);
	}
	
	/**
	 * 将当前默认权限设置为常规权限
	 */
	public RESULT updateDefaultRole(Integer organCode) {
		if (null == organCode)
			return RESULT.PARAMETER_ERROR;
		
		execute(sql_updateDefaultRole, organCode);
		return RESULT.SUCCESS;
	}
	
	/**
	 * 获取当前的默认权限（权限类别 = 默认）
	 */
	public Role getDefaultRole(Integer organCode) {
		if (null == Cache.organRoleMap.get(organCode) || Cache.organRoleMap.get(organCode).size() == 0)
			loadAllByOrgCode(organCode);
		
		for (Role p : Cache.organRoleMap.get(organCode)) {
			if (p.getIsDefault() && p.getOc().equals(organCode))
				return p;
		}
		return null;
	}
	
	/**
	 * 修改权限信息，为null的属性不修改
	 * @param	编辑完成的权限信息
	 */
	public RESULT update(Role role) {
		if (null == role || null == role.getCode())
			return RESULT.PARAMETER_ERROR;
		
		Role old = get(role.getCode());
		if (null == old)
			return RESULT.NOT_FIND;
		
		if (isNotNull(role.getName()))
			old.setName(role.getName());
		if (null != role.getIsDefault())
			old.setIsDefault(role.getIsDefault());
		if (isNotNull(role.getRemark()))
			old.setRemark(role.getRemark());
		if (null != role.getOc())
			old.setOc(role.getOc());
		
		RESULT result = upd(old);
		loadAllByOrgCode(role.getOc());
		return result;
	}
	
	/**
	 * 根据权限编号将其删除
	 * @param	要删除的权限编号
	 */
	public RESULT del(Integer roleCode,Integer oc) {
		if (null == roleCode)
			return RESULT.PARAMETER_ERROR;
		if (del(roleCode) == RESULT.SUCCESS) {
			execute(sql_delete, roleCode);
			loadAllByOrgCode(oc);
			return RESULT.SUCCESS;
		} else
			return RESULT.ERROR;
	}
	
	/**
	 * 删除指定的权限信息
	 * @param	要删除的权限信息对象
	 */
	public RESULT delete(Role role) {
		if (null == role || null == role.getCode())
			return RESULT.PARAMETER_ERROR;
		if (del(role) == RESULT.SUCCESS) {
			execute(sql_delete, role.getCode());
			loadAllByOrgCode(role.getOc());
			return RESULT.SUCCESS;
		} else
			return RESULT.ERROR;
	}
	
	/**
	 * 根据查询条件分页查询权限信息
	 * @param	查询条件
	 * @param	分页信息
	 */
	public RESULT findByMap(Integer oc, Map<String, String> map, PageBean pageBean) {
		
		if (null == oc) return null;
		
		Integer rootCode = organDAO.getRoot(oc).getCode();
		
		StringBuffer hql = new StringBuffer("FROM Role r WHERE 1=1 ");
		List<Object> list = null;
		if (map != null) {
			list = new ArrayList<Object>();
			String name = map.get(Parm.NAME);
//			String oc = map.get(Parm.OC);
//			String soncs = map.get(Parm.SON_LIST);
			if (isNotNull(name)) {
				hql.append(" AND r.name LIKE ?");
				list.add("%" + name + "%");
			}
//			if (isNotNull(oc)) {
//				hql.append(" AND r.oc = ?");
//				list.add(Integer.parseInt(oc));
//			}
			if (null != rootCode){
				hql.append(" AND r.oc = ?");
				list.add(rootCode);
			}
			
//			if (isNotNull(soncs)){
//				hql.append(" AND r.oc IN (?");
//				soncs = soncs.substring(1,soncs.length());
//				soncs = soncs.substring(0,soncs.length()-1);
//				list.add(organCode);
//				
//				String[] str = soncs.split(", ");
//				
//				for (int i = 0; i < str.length; i++) {
//					hql.append(", ?");
//					
//					list.add(Integer.parseInt(str[i]));
//				}
//				hql.append(" )");
//			}
			
			
		}		
		hql.append(" AND (r.deleted = 0 OR r.deleted IS NULL)");
		hql.append(" ORDER BY r.code");
		
		if (findToPageBean(hql.toString(), pageBean, list) == RESULT.SUCCESS)
			return RESULT.SUCCESS;
		
		return RESULT.ERROR;
	}
	
	/**
	 * 根据编号获取权限信息（内存操作）
	 * @param	要获取的权限信息编号
	 */
	public Role getByCode(Integer code,Integer oc) {
		if (null == code || null == oc) return null;
		
		Integer rootCode = organDAO.getRoot(oc).getCode();
		
		if (null == Cache.organRoleMap.get(rootCode) ||  Cache.organRoleMap.get(rootCode).size() == 0)
			loadAllByOrgCode(rootCode);
		
		for (Role p : Cache.organRoleMap.get(rootCode)) {
			if (p.getCode() == code)
				return p;
		}
		return null;
	}
	
	public Integer findName(String name,Integer oc){
		StringBuffer sql = new StringBuffer("FROM Role r WHERE r.name = ? AND r.oc = ?");
		List<Object> parm = new ArrayList<Object>();
		parm.add(name);
		parm.add(oc);
		List<Role> objList = find(sql.toString(), null, 1, parm.toArray());	
		return (null == objList || objList.size() == 0) ? null : Integer.parseInt(objList.get(0).getCode().toString());
	}

	@Autowired
	public void setOrganDAO(OrganDAO organDAO) {
		this.organDAO = organDAO;
	}
	
	
}
